package com.lys.emsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lys.emsystem.mapper.MenuMapper;
import com.lys.emsystem.entity.Menu;
import com.lys.emsystem.service.MenuService;
import com.lys.emsystem.utils.JWTUtils;
import com.lys.emsystem.utils.Result;
import com.lys.emsystem.vo.MenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;

    @Autowired
    private MenuMapper menuMapper;

    @PostMapping
    private Result search(@RequestBody MenuVo menuVo) {
        IPage<Menu> page = menuService.search(new Page(menuVo.getPageIndex(), menuVo.getPageSize()), menuVo);
        if (page.getTotal() > 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("totalCount", page.getTotal());
            map.put("menus", page.getRecords());
            return Result.buildResult(Result.Status.OK, map);
        } else {
            return Result.buildResult(Result.Status.NOT_FOUND);
        }
    }

    @PostMapping("/add")
    public Result add(@RequestBody Menu menu) {
        if (menuService.add(menu) == 1) {
            return Result.buildResult(Result.Status.OK);
        } else {
            return Result.buildResult(Result.Status.BAD_REQUEST);
        }
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Menu menu) {
        if (menuService.delete(menu.getId()) == 1) {
            return Result.buildResult(Result.Status.OK);
        } else {
            return Result.buildResult(Result.Status.BAD_REQUEST);
        }
    }

    @PostMapping("update")
    public Result update(@RequestBody Menu menu) {
        if (menuService.update(menu) == 1) {
            return Result.buildResult(Result.Status.OK);
        } else {
            return Result.buildResult(Result.Status.BAD_REQUEST);
        }
    }

    @PostMapping("/delList")
    public Result delList(@RequestBody MenuVo menuVo) {
        if (menuService.delList(menuVo.getIds()) > 0) {
            return Result.buildResult(Result.Status.OK);
        } else {
            return Result.buildResult(Result.Status.BAD_REQUEST);
        }
    }

    @GetMapping
    public Result getMenusList(@RequestHeader("token") String token) {
        Map<String, Object> map = JWTUtils.checkToken(token);
        List<Menu> menus = menuMapper.selectListByRole((Integer) map.get("roleId"));
        if (menus == null || menus.size() == 0) {
            return Result.buildResult(Result.Status.BAD_REQUEST);
        } else {
            return Result.buildResult(Result.Status.OK, menus);
        }
    }


}
